﻿define(['jquery','reg','api','AdministrativeDivisionOption'],function ($,reg,api,AdministrativeDivisionOption) {
    var CustomerAdd = {
        name: 'customer-add',
        template: ''
        + '<div>'
        + '<Modal title="新建客户"'
        + '       v-model="showCustomerAdd"'
        + '       width="340"'
        + '       v-on:on-cancel="cancelAdd"'
        + '       class-name="addClientWrap vertical-center-modal">'
        + '    <div class="modal-content">'
        + '        <ul class="pri-ul clearfix">'
        + '            <li class="pri-li">'
        + '                <span class="model-left">客户姓名</span>'
        + '                <p class="model-right">'
        + '                    <Poptip content="客户姓名不能为空" placement="right" v-model="poptipName">'
        + '                        <input type="text" id="customer" name="search" placeholder="某先生" v-model="customerInfo.nameText"'
        + '                               v-on:input="showGenderOption" v-on:propertychange="showGenderOption" v-on:click.stop="validateName" v-on:onblur="isNothing"/>'
        + '                    </Poptip>'
        + '                </p>'
        + '                <h3 class="c-shuru" v-show="showGender">'
        + '                    <em v-on:click="isMale">{{maleText}}</em>'
        + '                    <em v-on:click="isFemale">{{femaleText}}</em>'
        + '                </h3>'
        + '            </li>'
        + '            <li class="pri-li">'
        + '                <span class="model-left">客户属性</span>'
        + '                <p class="model-right">'
        + '                    <i-select v-model="type" >'
        + '                        <i-option v-for="item in typeOption" v-bind:value="item" :key="item">'
        + '                            {{item}}'
        + '                        </i-option>'
        + '                    </i-select>'
        + '                </p>'
        + '            </li>'
        + '            <li class="pri-li">'
        + '                <span class="model-left">客户归属</span>'
        + '                <p class="city model-right">'
        + '                    <Cascader v-bind:data="nodeOption" v-model="selectedNode"  filterable  v-bind:clearable="false" change-on-select ref="cascaderNode" v-bind:class="{ noChildren: isNoChildren }" v-on:on-change="selectNodeId"></Cascader>'
        + '                </p>'
        //+ '                <p class="model-right">'
        //+ '                    <i-select v-model="customerInfo.nodeId"  v-on:on-change="selectNodeId" filterable>'
        //+ '                        <i-option v-for="item in nodeOption" v-bind:value="item.Id" v-bind:key="item.NameText">{{item.NameText}}</i-option>'
        //+ '                    </i-select>'
        //+ '                </p>'
        + '                <Poptip content="必须选择客户归属" placement="right" v-model="poptipNodeId">'
        + '                </Poptip>'
        + '            </li>'
        + '            <li class="pri-li pri-li-disabled">'
        + '                <span class="model-left">是否成交</span>'
        + '                <p class="model-right">'
        + '                    <span>否</span>'
        + '                    <i></i>'
        + '                </p>'
        + '            </li>'
        + '            <li class="pri-li">'
        + '                <span class="model-left">添加时间</span>'
        + '                <p class="model-right">'
        + '                    <Row>'
        + '                        <Col>'
        + '                        <Date-picker type="date" placeholder="选择日期" :options="optionsDate" v-on:on-change="handleChange" v-bind:value="customerInfo.addTime"  v-bind:editable="false" v-bind:clearable="false"></Date-picker>'
        + '                        </Col>'
        + '                    </Row>'
        + '                </p>'
        + '            </li>'
        + '            <li class="pri-li">'
        + '                <span class="model-left">省份城市</span>'
        + '                <p class="city model-right">'
        + '                    <Cascader v-bind:data="area" v-model="selectedArea"  filterable  v-bind:clearable="false"></Cascader>'
        + '                </p>'
        + '                <Poptip content="必须选择客户所在城市" placement="right" v-model="poptipAreaCode">'
        + '                </Poptip>'
        + '            </li>'
        + '            <li class="pri-li">'
        + '                <span class="model-left">联系方式</span>'
        + '                <p class="model-right">'
        + '                    <Poptip v-bind:content="poptipPhoneContent" placement="right" v-model="poptipPhone">'
        + '                        <input type="text" v-model="customerInfo.phone"  v-on:click.stop="validatePhone"/>'
        + '                    </Poptip>'
        + '                </p>'
        + '            </li>'
        + '            <li class="pri-li">'
        + '                <span class="model-left">客户来源</span>'
        + '                <p class="model-right">'
        + '                    <i-select  v-model="customerInfo.sourceType">'
        + '                        <i-option v-for="item in sourceTypeOption" v-bind:value="item" v-bind:key="item">'
        + '                            {{item}}'
        + '                        </i-option>'
        + '                    </i-select>'
        + '                </p>'
        + '                <Poptip content="必须选择客户来源类型" placement="right" v-model="poptipSourceType">'
        + '                </Poptip>'
        + '            </li>'
        + '            <li class="pri-li">'
        + '                <span class="model-left">来源终端</span>'
        + '                <p class="model-right">'
        + '                    <i-select  style="width:100%" v-model="customerInfo.sourceClient">'
        + '                        <i-option v-for="item in sourceClientOption" v-bind:value="item.EnumValue" v-bind:key="item.Desction">'
        + '                            {{item.Desction }}'
        + '                        </i-option>'
        + '                    </i-select>'
        + '                </p>'
        + '            </li>'
        + '            <li class="pri-li">'
        + '                <span class="model-left">意向房源</span>'
        + '                <p class="model-right">'
        + '                    <i-select  style="width:100%" v-model="customerInfo.intentionHouse">'
        + '                        <i-option v-for="item in intentionHouseOption" v-bind:value="item.value" v-bind:key="item.text">'
        + '                            {{item.text }}'
        + '                        </i-option>'
        + '                    </i-select>'
        + '                </p>'
        + '            </li>'
        + '            <li class="pri-li-txta  li-txta">'
        + '                <span class="model-left">初始需求</span>'
        + '                <p class="model-right">'
        + '                    <textarea name="" v-model="customerInfo.initialDemand"></textarea>'
        + '                </p>'
        + '            </li>'
        + '            <li class=" pri-li-txta li-txta" style="float:left"><!--class=""-->'
        + '                <span class="model-left">客户备注</span>'
        + '                <p class="model-right">'
        + '                    <textarea name="" v-model="customerInfo.remark" v-on:click.stop="validateRemark">'
        + '                    </textarea>'
        + '                </p>'
        + '                <Poptip content="客户备注不能为空" placement="right" v-model="poptipRemark">'
        + '                </Poptip>'
        + '            </li>'
        + '            <li class="pri-li">'
        + '                <span class="model-left">客户等级</span>'
        + '                <p class="model-right">'
        + '                    <span>普通客户</span>'
        + '                    <i></i>'
        + '                </p>'
        + '            </li>'
        + '        </ul>'
        + '    </div>'
        + '    <div slot="footer">'
        + '        <Button size="large" long :loading="modal_loading" v-on:click.stop="saveCustomer" class="save-add-cusotmer-bntton">'
        + '            保存'
        + '        </Button>'
        + '    </div>'
        + '</Modal>'
        + '<!-- Confirm弹框begin-->'
        + '<Modal class="addCustomerConfirm" v-model="modalConfirm"'
        + '       width="360"'
        + '       v-bind:title="confirmTitle"'
        + '       v-bind:closable="false"'
        + '       v-bind:mask-closable="false"'
        + '       v-on:on-ok="confirmOk"'
        + '       class-name="addPublicWrap  vertical-center-modal confirm-add-again">'
        + '    <div class="modal-content">'
        + '        <ul class="pri-ul">'
        + '            <h3 class="warning" v-html="confirmContent">{{confirmContent}}</h3>'
        + '        </ul>'
        + '    </div>'
        + '</Modal>'
        + '<!--Confirm弹框end-->'
        + '</div>',
        props: {
            pool: {
                type: String,
                required: true
            }
        },
        data: function () {
            return {
                showCustomerAdd: false,
                type: this.pool === "私客池" || this.pool === "未知" ? "个人客户" : "公共客户",
                modal_loading: false,
                customerInfo: {
                    name: "",
                    nameText: "",
                    nodeId: "",
                    hasTrade: '否',
                    addTime: (new Date()).getFullYear() + "-" + ((new Date()).getMonth() + 1) + "-" + (new Date()).getDate(),
                    areaCode: "",
                    phone: "",
                    initialDemand: "",
                    remark: "",
                    intentionHouse: "",
                    sourceClient: 0,
                    sourceType: "",
                    gender: 0,
                    nodeType: this.pool === "部门池" ? 1: this.pool === "公司池" ? 2 : 0,
                },
                optionsDate: {
                    disabledDate(date) {
                        return date && date.valueOf() > Date.now();
                    }
                },
                modalConfirm: false,
                confirmTitle: "确认客户",
                confirmContent: "确认内容",

                initializeStaff: [],//初始员工
                initializeDept: [],//初始部门
                initializeCompany: [],//初始部门
                nodeOption:[],
                nodeStaffOption: [],//个人客户归属
                nodeDeptOption: [],//公共客户归属
                nodeCompanyOption: [],//公共客户归属
                nodeDeptAndCompanyOption: [],//公共客户归属
                selectedNode: [],//this.pool === "部门池" ? this.initializeDept : this.pool === "公司池" ? this.initializeCompany : this.initializeStaff,//所选的客户归属
                isNoChildren: true,//下拉框是否只有一列

                selectedArea: [],//所选的行政区域列表
                showGender: false,//是否显示性别选择框
                sourceClientOption: [],//客户来源终端选择项
                area: AdministrativeDivisionOption,//行政区域选择项
                sourceTypeOption: [],//客户来源类型选择项

                //验证
                poptipName: false,//客户客户姓名验证提示
                poptipPhone: false,
                poptipPhoneContent: "客户联系方式不能为空",
                poptipNodeId: false,
                poptipAreaCode: false,
                poptipRemark: false,
                poptipSourceType: false,


            }
        },
        computed: {
            femaleText: function () {
                return $.trim(this.customerInfo.nameText) + "女士";
            },
            maleText: function () {
                return $.trim(this.customerInfo.nameText) + "先生";
            },
            typeOption: function () {
                if (this.pool === "私客池") {
                    return ['个人客户'];
                }
                else if (this.pool === "未知") {
                    return ['个人客户', '公共客户'];
                }
                else {
                    return ['公共客户'];
                }
            },
            intentionHouseOption: function () {
                //#缺失部分#
                return [
                    { value: "f1", text: "房源1" },
                    { value: "f2", text: "房源2" },
                ];
            }
        },
        created: function () {
            var thisAdd = this;
            //ajax客户来源终端
            api.Get_Cusotmer_SourceClient()
                .done(function (data) {
                    if (data.IsSuccess) {
                        thisAdd.sourceClientOption = data.ResultObject;
                    } else {
                        thisAdd.$Message.error(data.ErrMsg);
                    }
                })
                .fail(function () {
                    thisAdd.$Message.error('查询出错');
                })
            api.Get_Customer_SourceType_Option()
                .done(function (data) {
                    if (data.IsSuccess) {
                        thisAdd.sourceTypeOption = data.ResultObject;
                    } else {
                        thisAdd.$Message.error(data.ErrMsg);
                    }
                })
                .fail(function () {
                    thisAdd.$Message.error('查询出错');
                })
        },
        mounted: function () {
            var thisAdd = this;
            //监听showCustomerAdd
            window.bus.$on("showCustomerAdd", function (data) {
                thisAdd.showCustomerAdd = true;
            });
            if (this.pool === "私客池" || this.pool === "未知") {
                api.Get_Staff_By_CompanyId({ companyId: localStorage.companyId })
                    .done(function (data) {
                        if (data.IsSuccess) {
                            thisAdd.nodeStaffOption = data.ResultObject;
                            thisAdd.initializeStaff = [localStorage.userId];
                            thisAdd.setNodeOption();
                        } else {
                            thisAdd.$Message.error(data.ErrMsg);
                        }
                    })
                    .fail(function () {
                        thisAdd.$Message.error('查询出错');
                    })
            }
            if (this.pool === "部门池" || this.pool === "未知" || this.pool === "公司池") {
                api.GetOrganizaitonNode({ "nodeId": localStorage.companyId })
                    .done(function (res) {
                        if (res.IsSuccess === true) {
                            thisAdd.initializeCompany = [localStorage.companyId];
                            thisAdd.nodeCompanyOption = [{ value: res.ResultObject.value, label: res.ResultObject.label }];
                            thisAdd.nodeDeptOption = res.ResultObject.children;
                            thisAdd.nodeDeptAndCompanyOption = [res.ResultObject];
                            thisAdd.initializeDept = thisAdd.readNodeTree(res.ResultObject, localStorage.deptPoolNodeId);
                            if (this.pool === "部门池") {
                                thisAdd.initializeDept.shift();
                            }
                            thisAdd.setNodeOption();
                        } else {
                            thisAdd.$Message.error(res.ErrMsg);
                        }
                    })
                    .fail(function () {
                        thisAdd.$Message.error('查询出错');
                    });
            }
            //if (this.pool === "部门池" || this.pool === "未知") {

            //    $.get("/Department/GetDepartmentByCompanyId", { companyId: localStorage.companyId },  function (data) {
            //        if (data.IsSuccess) {
            //            thisAdd.nodeDeptOption = data.ResultObject;
            //            thisAdd.nodeDeptAndCompanyOption = thisAdd.nodeCompanyOption.concat(thisAdd.nodeDeptOption);
            //        } else {
            //            thisAdd.$Message.error(data.ErrMsg);
            //        }
            //    });
            //}
            //if (this.pool === "公司池" || this.pool === "未知") {
            //    $.get("/Company/GetCompanyById", { companyId: localStorage.companyId }, function (data) {
            //        if (data.IsSuccess) {
            //            thisAdd.nodeCompanyOption.push(data.ResultObject);
            //            thisAdd.nodeDeptAndCompanyOption = thisAdd.nodeCompanyOption.concat(thisAdd.nodeDeptOption);
            //        } else {
            //            thisAdd.$Message.error(data.ErrMsg);
            //        }
            //    });
            //}
        },
        watch: {
            selectedArea: function (newArea) {
                newArea.length === 0 ? this.customerInfo.areaCode = "" : this.customerInfo.areaCode = newArea[newArea.length - 1];
            },
            selectedNode: function (newNode) {
                newNode.length === 0 ? this.customerInfo.nodeId = "" : this.customerInfo.nodeId = newNode[newNode.length - 1];
            },
            type: function () {
                this.setNodeOption();
            }
        },
        methods: {
            readNodeTree:function(node,id)
            {
                if (node.value == id){
                    return [id];
                }
                var arr = [];
                if (node.children && node.children.length > 0) {
                    for (var i = 0; i < node.children.length; i++) {
                        arr = this.readNodeTree(node.children[i], id);
                        if (arr.length > 0) {
                            arr.unshift(node.value);
                            break;
                        } else {
                            continue;
                        }
                    }
                }
                return arr;
            },
            setNodeOption: function () {
                if (this.type === "个人客户") {
                    this.customerInfo.nodeId = localStorage.userId;
                    this.selectedNode = this.initializeStaff;
                    this.nodeOption = this.nodeStaffOption;
                    this.customerInfo.nodeType = "0";
                    this.isNoChildren = true;
                }
                else {
                    this.customerInfo.nodeType = "1";
                    if (this.pool === "部门池") {
                        this.customerInfo.nodeId = localStorage.deptPoolNodeId;
                        this.selectedNode = this.initializeDept;
                        this.nodeOption = this.nodeDeptOption;
                        var c = 0;
                        for (var i = 0; i < this.nodeOption.length; i++){
                            if (this.nodeOption[i].children && this.nodeOption[i].children.length > 0) {
                                c = 1;
                                break;
                            }
                        }
                        this.isNoChildren = c===0;
                    } else if (this.pool === "公司池") {
                        this.customerInfo.nodeId = localStorage.companyId;
                        this.selectedNode = this.initializeCompany;
                        this.nodeOption = this.nodeCompanyOption;
                        this.isNoChildren = true;
                    } else {
                        this.customerInfo.nodeId = localStorage.deptPoolNodeId;
                        this.selectedNode = this.initializeDept;
                        this.nodeOption = this.nodeDeptAndCompanyOption
                        this.isNoChildren = false;
                    }
                }
                this.$nextTick(function() {
                    this.$refs.cascaderNode.updateSelected(true);
                });
            },
            cancelAdd() {
                //触发search
                bus.$emit("search",true);
            },
            handleChange: function (date) {
                this.customerInfo.addTime = date;
            },
            showGenderOption: function () {
                if ($.trim(this.customerInfo.nameText) != "") {
                    this.showGender = true;
                }
            },
            isMale: function () {
                if ($.trim(this.customerInfo.nameText) != "") {
                    this.customerInfo.gender = 0;
                    this.customerInfo.name = $.trim(this.customerInfo.nameText);
                    this.customerInfo.nameText = this.maleText;
                }
                else {
                    this.customerInfo.name = "";
                    this.customerInfo.nameText = "";
                }
                this.showGender = false;
            },
            isFemale: function () {
                if ($.trim(this.customerInfo.nameText) != "") {
                    this.customerInfo.gender = 1;
                    this.customerInfo.name = $.trim(this.customerInfo.nameText);
                    this.customerInfo.nameText = this.femaleText;
                }
                else {
                    this.customerInfo.name = "";
                    this.customerInfo.nameText = "";
                }
                this.showGender = false;
            },
            isNothing: function () {
                if (this.customerInfo.name === "" && this.showGender == false){
                    this.customerInfo.name = $.trim(this.customerInfo.nameText)
                }
            },
            selectNodeId: function (value) {
                //var v = value[value.length - 1];
                //var nodetype = this.checkNodeId(v, this.nodeOption)
                //if (nodetype != ""){
                //    this.customerInfo.nodeType = nodetype;
                //}
            },
            //checkNodeId: function (value, nodeOption) {
            //    var nodetype = "";
            //    for (var i = 0; i < nodeOption.length; i++) {
            //        if (value === nodeOption[i].value) {
            //            return nodeOption[i].NodeType;
            //        } else {
            //            nodetype = this.checkNodeId(value, nodeOption[i].children)
            //            if (nodetype != "") {
            //                return nodetype;
            //            }
            //        }
            //    }
            //    return nodetype;
            //},
            validateAll: function () {
                var isFail = false;
                isFail = isFail || this.validateName();
                isFail = isFail || this.validateNodeId();
                isFail = isFail || this.validateAreaCode();
                isFail = isFail || this.validatePhone();
                isFail = isFail || this.validateSourceType();
                isFail = isFail || this.validateRemark();
                return isFail;
            },
            validateName: function () {
                if ($.trim(this.customerInfo.nameText) != "") {
                    return this.poptipName = false;
                }
                else {
                    return this.poptipName = true;
                }
            },
            validatePhone: function () {
                var phoneValue = $.trim(this.customerInfo.phone);
                if (phoneValue != "") {
                    if (reg.checkPhone(phoneValue)) {
                        this.poptipPhoneContent = "手机号码错误";
                        return this.poptipPhone = true;
                    }
                    return this.poptipPhone = false;
                }
                else {
                    this.poptipPhoneContent = "客户联系方式不能为空";
                    return this.poptipPhone = true;
                }
            },
            validateNodeId: function () {
                if (this.customerInfo.nodeId != "") {
                    return this.poptipNodeId = false;
                }
                else {
                    return this.poptipNodeId = true;
                }
            },
            validateAreaCode: function () {
                if ($.trim(this.customerInfo.areaCode) != "") {
                    return this.poptipAreaCode = false;
                }
                else {
                    return this.poptipAreaCode = true;
                }
            },
            validateSourceType: function () {
                if ($.trim(this.customerInfo.sourceType) != "") {
                    return this.poptipSourceType = false;
                }
                else {
                    return this.poptipSourceType = true;
                }
            },
            validateRemark: function () {
                if ($.trim(this.customerInfo.remark) != "") {
                    return this.poptipRemark = false;
                }
                else {
                    return this.poptipRemark = true;
                }
            },
            initializeData: function () {
                this.customerInfo.name = "";
                this.customerInfo.nameText = "";
                //this.customerInfo.type = this.pool === "私客池" || this.pool === "未知" ? "个人客户" : "公共客户";
                //this.customerInfo.nodeId = this.pool === "部门池" ? localStorage.deptPoolNodeId : this.pool === "公司池" ? localStorage.companyPoolNodeId : localStorage.userId;
                //this.customerInfo.hasTrade = '否';
                //this.customerInfo.addTime = (new Date()).getFullYear() + "-" + ((new Date()).getMonth() + 1) + "-" + (new Date()).getDate();
                this.selectedArea = [];
                this.customerInfo.phone = "";
                this.customerInfo.initialDemand = "";
                this.customerInfo.remark = "";
                this.customerInfo.intentionHouse = "";
                this.customerInfo.sourceClient = 0;
                this.customerInfo.sourceType = "";
                this.customerInfo.gender = 0;
            },
            saveCustomer: function () {
                var thisCustomer = this;
                if (thisCustomer.validateAll()) {
                    return;
                } else {
                    api.Get_Check_Customer_Exists({contactValue: thisCustomer.customerInfo.phone})
                        .done(function (data) {
                            if (data.IsSuccess) {
                                if (data.ResultObject != "") {
                                    thisCustomer.confirmTitle = "确认是否继续添加客户";
                                    thisCustomer.confirmContent = data.ResultObject;
                                    thisCustomer.modalConfirm = true;
                                } else {
                                    thisCustomer.saveCustomerPostRequest();
                                }
                            } else {
                                thisCustomer.$Message.error(data.ErrMsg);
                            }
                        })
                        .fail(function () {
                            thisCustomer.$Message.error('查询出错');
                        })
                }
            },
            saveCustomerPostRequest: function () {
                var thisCustomer = this;
                thisCustomer.modal_loading = true;
                api.Post_Add_Customer(thisCustomer.customerInfo)
                    .done(function (data) {
                        if (data.IsSuccess) {
                            thisCustomer.$Message.success('保存成功');
                            thisCustomer.initializeData();
                            thisCustomer.modal_loading = false;
                        } else {
                            thisCustomer.$Message.error(data.ErrMsg);
                            thisCustomer.modal_loading = false;
                        }
                    })
                    .fail(function () {
                        thisCustomer.$Message.error('保存失败');
                        thisCustomer.modal_loading = false;
                    })
            },
            confirmOk: function () {
                this.saveCustomerPostRequest(this);
            }

        }
    };
    return CustomerAdd;
});
